"ui";
ui.layout(
    `<drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="AI获客远控客户端" />
            </appbar>
            <viewpager id="viewpager">
                <frame>
                    <vertical padding="15 10" bg="#e3e0e0">
                        <ScrollView h="auto" layout_weight="25">
                            <vertical h="auto" layout_weight="25">
                                <card contentPadding="50px 20px 50px 20px" cardBackgroundColor="#ffffff" cardCornerRadius="15px" cardElevation="15px">
                                    <vertical id="deiveceBaseInfo" visibility="visible">
                                        <text text="基本信息:" textSize="20sp" textColor="#210303" marginBottom="5px" />
                                        <horizontal h="80px">
                                            <text text="设备UUID:" textColor="#210303" textSize="14sp" h="*" w="350px" gravity="left|center" layout_weight="1" />
                                            <text id="设备UUID" text="" textColor="#210303" textSize="14sp" h="*" w="*" marginLeft="15px" gravity="left|center" layout_weight="2" />
                                        </horizontal>
                                        <horizontal h="80px">
                                            <text text="服务端IP:" textSize="14sp" h="*" w="350px" gravity="left|center" layout_weight="1" />
                                            <input id="服务端IP" inputType="text" hint="请输入服务端ip" textSize="14sp" h="*" w="*" margin="0" bg="#ffffff" padding="15px 0 0 0" gravity="left|center" layout_weight="2" />
                                        </horizontal>
                                        <horizontal h="80px">
                                            <text text="服务端Port:" textSize="14sp" h="*" w="350px" gravity="left|center" layout_weight="1" />
                                            <input id="服务端Port" inputType="text" hint="服务端Port,默认9998" textSize="14sp" h="*" w="*" margin="0" bg="#ffffff" padding="15px 0 0 0" gravity="left|center" layout_weight="2" />
                                        </horizontal>
                                        <horizontal h="80px">
                                            <text text="访问密码:" textSize="14sp" h="*" w="350px" gravity="left|center" layout_weight="1" />
                                            <input id="访问密码" inputType="text" hint="WEB端操作设备所需" textSize="14sp" h="*" w="*" margin="0" bg="#ffffff" padding="15px 0 0 0" gravity="left|center" layout_weight="2" />
                                        </horizontal>
                                    </vertical>
                                </card>
                                <card id="notice" visibility="visible" contentPadding="50px 20px 50px 20px" marginTop="30px" cardBackgroundColor="#ffffff" cardCornerRadius="15px" cardElevation="15px">
                                    <vertical>
                                        <text text="公告:" textSize="20sp" textColor="#210303" marginBottom="5px" />
                                        <horizontal>
                                            <text id="NOTICE_MSG" text="" textColor="#210303" textSize="14sp" h="*" w="*" gravity="left|center" layout_weight="1" />
                                        </horizontal>
                                    </vertical>
                                </card>
                            </vertical>
                        </ScrollView>
                        <horizontal layout_weight="1" gravity="center" marginTop="30px">
                            <button id="saveSetting" layout_gravity="center" text="保存配置" style="Widget.AppCompat.Button.Colored" bg="#ff5723" marginLeft="1px" marginRight="1px" foreground="?selectableItemBackground"/>
                            <button id="startScript" layout_gravity="center" text="启动程序" style="Widget.AppCompat.Button.Colored" bg="#04a9f5" marginLeft="1px" marginRight="1px" foreground="?selectableItemBackground"/>
                        </horizontal>
                    </vertical>
                </frame>
            </viewpager>
        </vertical>
    </drawer>`
);


//设置滑动页面的标题
//让滑动页面和标签栏联动
activity.setSupportActionBar(ui.toolbar)

let config = require('./common/config.js')
// 导入公共常量类
let commonConstant = require('./common/commonConstant.js')
// 公共储存对象
var commonStorage = storages.create("zjh336.cn" + config.commonScriptKey);
let utils = require('./common/utils.js')
let deviceUUID = utils.getDeviceUUID()
ui['设备UUID'].attr('text', deviceUUID)


importClass("android.content.pm.PackageManager");
importClass("android.provider.Settings");
let myPackageName = context.getPackageName();

// 当前版本信息
let curVersionName = app.versionName
let defaultIP = "127.0.0.1";
let defaultPORT = "9998";


function getDefaultInfo(){
	// 服务端校验地址
	let serverUrl = "https://gitee.com/zjh336/zjh336_limit/raw/master/gjx/serverInfo.json?t=" + (new Date().getTime());
	try {
		let serverResult = http.get(serverUrl);
		if (serverResult.statusCode !== 200) {
			return;
		}
		let resutlJson = serverResult.body.string();
		if (!resutlJson) {
			return;
		}
		let resultObj = JSON.parse(resutlJson);
		if (!resultObj) {
			return;
		}
		let IP = resultObj.IP;
		let PORT = resultObj.PORT;
		let NOTICE_MSG = resultObj.NOTICE_MSG;

		if (NOTICE_MSG) {
			ui["notice"].attr("visibility", "visible");
			ui["NOTICE_MSG"].attr("text", "1、本工具为AI获客软件的远控客户端，可通过服务端(浏览器访问http://服务端IP:服务端Port)，远程控制安装了本应用的设备。\r\n2、本工具初次启动时，需要设置相应权限(见5-8)，可以选择手动设置，也可以点击启动程序按钮后，按步骤赋予权限。\r\n3、权限设置一次后，无需再次设置，打开APP后将自动启动程序，连接服务端。\r\n4、可修改服务端地址(联系客服获取)，点击保存设置即可。\r\n5、本工具依赖无障碍服务功能,可选择手动开启。\r\n6、本工具需要开启悬浮窗权限,可选择手动开启。\r\n7、本工具需要设置省电模式为无限制,保持存活状态,可选择手动开启。\r\n8、本工具需要设置后台运行权限,必须手动开启(权限设置,后台弹出权限)。");
		} else {
			ui["notice"].attr("visibility", "gone");
		}
		defaultIP = "127.0.0.1";
		defaultPORT = PORT;
	} catch (e) {
		console.error(e);
		return;
	}
}


function setAutoService() {
    if (!auto.service) {
        if (checkPermission("android.permission.WRITE_SECURE_SETTINGS")) {
            openAccessibility();
        } else {
            if ($shell.checkAccess("adb")) {
                shell("pm grant " + myPackageName + " android.permission.WRITE_SECURE_SETTINGS", {
                    adb: true,
                });
                toastLog("adb授权成功");
                openAccessibility();
            } else {
                if ($shell.checkAccess("root")) {
                    shell("pm grant " + myPackageName + " android.permission.WRITE_SECURE_SETTINGS", {
                        root: true,
                    });
                    toastLog("root授权成功");
                    openAccessibility();
                } else {
                    console.info("\n也可使用WRITE_SECURE_SETTINGS权限开启无障碍服务\n授权代码已复制，使用adb激活");
                    setClip("adb shell pm grant " + myPackageName + " android.permission.WRITE_SECURE_SETTINGS");
                    app.startActivity({
                        action: "android.settings.ACCESSIBILITY_SETTINGS",
                    });
                    toastLog("请先开启无障碍服务,选择华仔AutoJs工具相极速版");
                }
            }
        }
    }
}

function openAccessibility() {
    let mServices = ":" + myPackageName + "/com.stardust.autojs.core.accessibility.AccessibilityService";
    let enabledServices = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
    enabledServices = enabledServices ? enabledServices.replace(new RegExp(mServices, "g"), "") : "";
    Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "");
    Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, enabledServices + mServices);
}

function checkPermission(permission) {
    pm = context.getPackageManager();
    return PackageManager.PERMISSION_GRANTED == pm.checkPermission(permission, context.getPackageName().toString());
}

function checkSystemService(service) {
    importClass(android.app.AppOpsManager);
    appOps = context.getSystemService(context.APP_OPS_SERVICE);
    mode = appOps.checkOpNoThrow("android:get_" + service, android.os.Process.myUid(), context.getPackageName());
    return (granted = mode == AppOpsManager.MODE_ALLOWED);
}

function refreshCacheAndUi(){
	let IP = commonStorage.get("服务端IP") || defaultIP;
    let PORT = commonStorage.get("服务端Port") || defaultPORT;

	commonStorage.put("服务端IP", IP);
	commonStorage.put("服务端Port", PORT);
	
     // 读取公共缓存数据
    utils.getUICacheData(commonConstant.commonSettingKey, commonStorage)
}


// 加载服务端信息
function loadServerInfo() {

    // 自动开启前台服务
    $settings.setEnabled("foreground_service", true);

    // 没有悬浮窗权限时 自动开启
    if (!floaty.checkPermission()) {
        //没有权限时去打开悬浮窗5
        let mIntent = app.intent({
            action: "android.settings.action.MANAGE_OVERLAY_PERMISSION",
            data: "package:" + context.getPackageName(),
        });
        //这里把数字1作为标记
        activity.startActivityForResult(mIntent, 1);
    }

    // 自动开启无障碍服务
    setAutoService();
	
	// 加载服务端默认信息
    getDefaultInfo();

	// 刷新本地缓存和UI显示
    refreshCacheAndUi();
}


// 初始化ui设置
function initUiSetting() {

    let 服务端IP = commonStorage.get('服务端IP')
    if (服务端IP) {
        startScriptFun()
        // 开启了自动运行后回到主页
        if (auto.service) {
            home();
        }
    } else {
		// 首次进入没有服务端信息 加载服务端默认信息
		getDefaultInfo();

		// 刷新本地缓存和UI显示
		refreshCacheAndUi();
	}
}


// 开始脚本
function startScriptFun(callback) {
    // 每次开始之前加载一次服务端信息
    loadServerInfo();

    let remoteIp = commonStorage.get("服务端IP");
    if (remoteIp) {
        const btnContent = ui.startScript.attr("text")
        toast(btnContent)
        const afterBtnContent = "启动程序" === btnContent ? "停止程序" : "启动程序"
        ui.startScript.attr("text", afterBtnContent)
        if (btnContent === "启动程序") {
            runScript = engines.execScriptFile("./runScript.js");

            // 唤醒设备
            device.wakeUpIfNeeded();
            // 保持常亮
            device.keepScreenOn();
        } else {
            const myScript = engines.myEngine()
            const all = engines.all()
            all.forEach(item => {
                if (item.id !== myScript.id) {
                    item.forceStop()
                }
            });
            utils.timerStopPushLog();
        }
    }
}

// 初始化ui
initUiSetting()
ui.startScript.on("click", () => {
    startScriptFun()
})

// 保存设置按钮
ui.saveSetting.on("click", () => {
    // 设置公共缓存数据
    utils.setUICacheData(commonConstant.commonSettingKey, commonStorage)
    toastLog("保存成功！")
})


// 刷新ui
events.broadcast.on("refreshUI", function() {
    // 读取公共缓存数据
    utils.getUICacheData(commonConstant.commonSettingKey, commonStorage)
});


function getCurrentTime() {
    var date = new Date(); //当前时间
    var month = zeroFill(date.getMonth() + 1); //月
    var day = zeroFill(date.getDate()); //日
    var hour = zeroFill(date.getHours()); //时
    //当前时间
    var curTime = date.getFullYear() + month + day +
        hour;
    return curTime;
}

function zeroFill(i) {
    if (i >= 0 && i <= 9) {
        return "0" + i;
    } else {
        return String(i);
    }
}


let waitTimes = 0
files.createWithDirs("/sdcard/autoJsToolsLog/")
// 获取当前时间字符串
let currenTimes = getCurrentTime()
console.setGlobalLogConfig({
    file: "/sdcard/autoJsToolsLog/log" + currenTimes + ".txt"
})

threads.start(() => {
    try {
        while (true) {
            sleep(1000)
            let tempTimes = getCurrentTime()
            if (currenTimes !== tempTimes) {
                currenTimes = tempTimes
                console.setGlobalLogConfig({
                    file: "/sdcard/autoJsToolsLog/log" + currenTimes + ".txt"
                })
            }
        }
    } catch (error) {
        console.error("错误", error)
    }
})
if (!$power_manager.isIgnoringBatteryOptimizations()) {
    console.log("未开启忽略电池优化，尝试申请权限");
    $power_manager.requestIgnoreBatteryOptimizations();
}
// 监听广播
var receiver = new JavaAdapter(android.content.BroadcastReceiver, {
    onReceive: function(context, intent) {
        switch (intent.action) {
            case Intent.ACTION_CONFIGURATION_CHANGED:
                events.broadcast.emit("orientationchange", '');
                break;
        }
    },
});
var filter = new IntentFilter();
// 屏幕旋转
filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
context.registerReceiver(receiver, filter);
events.on("exit", function() {
    receiver && context.unregisterReceiver(receiver);
});

function strToArr(str) {
    if (!str) {
        return [];
    }
    //防止保活时,连环回调放入空字符,去掉末尾没用的字符串
    return str.replace(/:$/, "").split(":");
}
try {
    importClass(android.os.Handler);
    importClass(android.database.ContentObserver);
    let curPackage = auto.service ? currentPackage() : "com.zjh336.cn.tools.simple"

    //保活白名单数组,也可以时其他应用的服务名,这里是autojspro的
    const whiteList = [curPackage + "/com.stardust.autojs.core.accessibility.AccessibilityService"];
    const contentResolver = context.getContentResolver();
    let lastArr = strToArr(Settings.Secure.getString(contentResolver, "enabled_accessibility_services"));
    let contentObserver = JavaAdapter(
        ContentObserver, {
            onChange(b) {
                let service = "";
                let str = Settings.Secure.getString(contentResolver, "enabled_accessibility_services");
                let newArr = strToArr(str);
                if (newArr.length > lastArr.length) {
                    newArr.some(item => {
                        service = item;
                        return !lastArr.includes(item);
                    });
                    console.log("开启了----", service);
                } else if (newArr.length < lastArr.length) {
                    lastArr.some(item => {
                        service = item;
                        return !newArr.includes(item);
                    });
                    //这里可以做一些保活处理
                    if (service && whiteList.includes(service)) {
                        try {
                            newArr.push(service);
                            let success = Settings.Secure.putString(contentResolver, "enabled_accessibility_services", newArr.join(":"));
                            console.log(`${success ? "保活成功" : "保活失败"}----${service}`);
                        } catch (error) {
                            console.log("没有权限----", error);
                        }
                    } else {
                        console.log("关闭了----", service);
                    }
                }
                lastArr = newArr;
            },
        },
        new Handler()
    );
    contentResolver.registerContentObserver(Settings.Secure.getUriFor("enabled_accessibility_services"), true, contentObserver);
    events.on("exit", () => {
        contentResolver.unregisterContentObserver(contentObserver);
    });
} catch (e) {
    console.error(e);
}
//保持脚本运行
setInterval(() => {}, 1000);